import { ETaskState } from "GameLoop/DecisionMaking/TaskDeclare/type";
import { ATeamEntity } from "GameLoop/WorldState/EntityManager/Entitys/team";

export class TaskConditions
{
    private static conditions:ITaskCondition<TaskCondition>={
        timeout: TaskConditions.checkTimeout,
        taskFlag: TaskConditions.checkTaskFlag,
        wipeOut:TaskConditions.checkWipeoutEnemy
    }

    public static isComplete(room:Required< Room>,task:ITask)
    {
        const thisfunction = this.conditions[(task.condition as ConditionArg).type];
        if(!thisfunction)
        {
            global.Log.Error(`未定义的结束条件`);
        }
        return thisfunction(room,task,(task.condition as ConditionArg).param);
    }

    public static checkTimeout(room:Required< Room>,task:ITask,param:any=undefined):number
    {
        if(task.ttl == 0)
        {
            return ETaskState.Complete;
        }
        else if(task.ttl <0)
        {
            return ETaskState.Running;
        }else  
        {
            task.ttl --;
            return ETaskState.Running;
        }
    }

    private static checkTaskFlag(room:Required< Room>,task:ITask,param:any):number
    {
        if(Game.flags[task.id])
        {
            return ETaskState.Running;
        }
        return ETaskState.Complete;
    }

    private static checkWipeoutEnemy(room:Required< Room>,task:ITask<ITeamTaskData<"defend">>,param:any):number
    {
        if(task.data.arg.enemy .length== 0 && task.data.arg.structures.length ==0  )
        {
            const creepcount = _.sum (_.flatten(Object.values(task.data.teams)),e=>(room.getEntityByID(e) as ATeamEntity).creeps.length);
            if(creepcount ==0)
            {
                room.log("info",`外矿防守任务 完成${JSON.stringify(task)}`);
                return ETaskState.Complete
            }
        }
        return ETaskState.Running;
    }

}